from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from .. import db, login_manager

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(512))
    is_admin = db.Column(db.Boolean, default=False)  # 添加管理员标志
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 新增字段
    name = db.Column(db.String(64))  # 真实姓名
    phone = db.Column(db.String(20))  # 电话号码
    organization = db.Column(db.String(120))  # 所属组织
    is_active = db.Column(db.Boolean, default=True)  # 账号是否激活
    last_login = db.Column(db.DateTime)  # 最后登录时间
    
    # 重置密码相关字段
    reset_password_token = db.Column(db.String(40), unique=True)
    reset_password_expires = db.Column(db.DateTime)
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
        
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
    
    def update_last_login(self):
        self.last_login = datetime.utcnow()
        db.session.commit()

@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id)) 